package com.etc.test4.dao;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author MaZheng
 * @since 2020/12/7 - 15:24
 */
public class DBUtil {
    private static DruidDataSource dataSource;

    static {
        dataSource = new DruidDataSource();

        // 获取类加载器。 加载文件 返回输入流
        InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");

        // hashtable  线程安全，key和value不可为null
        Properties props = new Properties();
        try {
            props.load(is);
            dataSource.setConnectProperties(props);
            dataSource.setUrl(props.getProperty("url"));
            dataSource.setDriverClassName(props.getProperty("driverClassName"));
            dataSource.setUsername(props.getProperty("username"));
            dataSource.setPassword(props.getProperty("password"));
            // ...
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 每个线程的 缓冲区 数据
    private static ThreadLocal<Connection> local = new ThreadLocal<>();
    public static Connection getConnection() {
        try {
            Connection conn = dataSource.getConnection();
            local.set(conn);
            return conn;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
    public static void close() {

        Connection conn = local.get();
        try {
            conn.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Connection conn = DBUtil.getConnection();

        try {
            ResultSet rs = conn.createStatement().executeQuery("select now() ");
            rs.next();
            System.out.println(rs.getString(1));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        DBUtil.close();
    }
}
